<template>
  <div class="app-container">
    <div class="drug-statistics">
      <!-- 左边，药品分类 -->
      <div class="container-left">
        <ul class="tabs">
          <template v-for="(item, index) in drugTypes">
            <li
              :class="query.drugType === item.id ? ['tabs-item','active']:['tabs-item']"
              @click="onTabClick(item.id)"
              :key="index"
            >
              <span>{{ item.text }}({{ item.sum }})</span>
            </li>
          </template>
        </ul>
      </div>
      <div class="container-right">
        <!-- 搜索区域 -->
        <div class="head-container">
          <div class="form-head">
            <!-- 药品名称 -->
            <el-input
              v-model="query.drugName"
              placeholder="药品名称"
              style="width: 150px"
              class="filter-item"
              :clearable="true"
              size='small'
            />
            <!-- 调取方式 -->
            <el-select
              style="width: 150px"
              v-model="query.type"
              class="filter-item"
              :clearable="false"
            >
              <template v-for="item in typeList">
                <el-option
                  :label="item.text"
                  :value="item.id"
                  :key="item.id"
                />
              </template>
            </el-select>
            <!-- 时间 -->
            <datePicker
              @change="onChangeTime"
              v-model="defaultDate"
              :type="query.type"
              class="date-item"
              ref="datePicker"
            />
            <!-- 搜索按钮 -->
            <span>
              <el-button
                class="filter-item"
                size="mini"
                type="success"
                icon="el-icon-search"
                @click="onQuery"
              >
                搜索
              </el-button>
              <el-button
                class="filter-item"
                size="mini"
                type="warning"
                icon="el-icon-refresh-left"
                @click="onResetQuery"
              >
                重置
              </el-button>
            </span>
          </div>
          <div class="form-right">
            <el-button
              icon="el-icon-download"
              :loading="loading"
              @click="onExport"
              type="primary"
              size="mini"
            >导出数据</el-button>
          </div>
        </div>
        <!--表格渲染 @sort-change="crud.sortChange" -->
        <div class="table">
          <tableStatistics
            :summaryMethod="summaryMethod"
            v-loading="crud.loading"
            ref="tableStatistics"
            :columns="columns"
            :data="crud.data"
            showSummary
          >
            <template slot="drugType" slot-scope="scope">
              <drugType :value="scope.row.drugType" />
            </template>
            <template slot="price" slot-scope="scope">
              {{ formatMoney(scope.row.price, 2) }}
            </template>
            <template slot="costPrice" slot-scope="scope">
              {{ formatMoney(scope.row.costPrice, 2) }}
            </template>
            <template slot="profit" slot-scope="scope">
              {{ formatMoney(scope.row.profit, 2) }}
            </template>
          </tableStatistics>
        </div>
        <!-- 分页 -->
        <pagination />
      </div>
    </div>
  </div>
</template>

<script>
import { getDrugTypes, getCountByDrugType } from '@/api/storageRoom/drug';
import drugType from "@/views/storageRoom/drug/module/drugType";
import { columns, typeList } from '@/const/drugStatistics';
import { exportDrugStatis } from "@/api/statistics/index";
import CRUD, { presenter, header } from '@crud/crud';
import tableStatistics from "../components/table";
import rrOperation from '@crud/RR.operation';
import { formatMoney } from "@/utils/index";
import datePicker from '../components/date';
import pagination from '@crud/Pagination';

let defaultCrud = CRUD({
  queryOnPresenterCreated: false,
  title: '药房药品',
  url: 'drugStatistics/findStatistics',
  method: 'post',
  query: {
    startTime: null,
    drugName: null,
    endTime: null,
    drugType: 0,
    type: 0
  }
});

export default {
  name: "drugStatistics",
  components: {
    tableStatistics,
    rrOperation,
    pagination,
    datePicker,
    drugType
  },
  mixins: [
    presenter(defaultCrud),
    header()
  ],
  data() {
    return {
      drugTypes: [
        {id: 0, text: "全部", sum: 0}
      ],
      statisticsSum: null,
      defaultDate: null,
      loading: false, // 操作按钮防重复提交
      typeList,
      columns,
    };
  },
  mounted() {
    this._searchType();

    if(this.query.startTime && this.query.endTime) {
      this.defaultDate = [
        this.query.startTime,
        this.query.endTime
      ];
    }
  },
  methods: {
    formatMoney,
    [CRUD.HOOK.dataLoadSuccess](crud, list, data) {
      this.statisticsSum = data.statisticsSum;
    },
    [CRUD.HOOK.afterRefresh]() {
      this.$nextTick(() => {
        this.$refs.tableStatistics.resizeListener();
      });
    },
    onQuery() {
      if(!this.query.startTime || !this.query.endTime) {
        this.$message.error('请筛选时间范围');
        return;
      }
      this.crud.toQuery();
      if(this.drugTypes.length > 1) {
        this._searchCountByDrugType();
      }
    },
    onTabClick(value) {
      this.query.drugType = value;
      if(this.query.startTime && this.query.endTime) {
        this.onQuery();
      }
    },
    // 时间处理
    onChangeTime() {
      if(this.defaultDate && this.defaultDate.length) {
        this.query.startTime = this.defaultDate[0];
        this.query.endTime = this.defaultDate[1];
        this.onQuery();
      } else {
        this.query.startTime = null;
        this.query.endTime = null;
      }
    },
    // 重置
    onResetQuery() {
      this.defaultDate = null;
      this.crud.resetQuery(false);
    },
    // 导出
    onExport() {
      exportDrugStatis(this.query);
    },
    // 合计
    summaryMethod({ columns, data }) {
      let res = [];
      columns.forEach(column => {
        switch(column.property) {
          case "drugName":
            res.push("总计");
            break;
          case "costPrice":
          case "price":
          case "profit":
            if(this.statisticsSum && this.statisticsSum[column.property]) {
              res.push(this.formatMoney(this.statisticsSum[column.property], 2));
            } else {
              res.push("0");
            }
            break;
          default:
            res.push("/");
            break;
        }
      });
      return res;
    },
    // 药品分类
    _searchType() {
      getDrugTypes().then(res => {
        res.forEach(item => {
          this.drugTypes.push({
            text: item.label,
            id: item.value,
            sum: 0
          });
        });
        this._searchCountByDrugType();
      });
    },
    _searchCountByDrugType() {
      let data = {
        pharmacyId: this.query.pharmacyId
      };
      getCountByDrugType(data).then(res => {
        res.forEach(item => {
          this.drugTypes[item.drugType].sum = item.total;
        });
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 84px);
  background: #F5F5F5;
  padding: 15px;

  .drug-statistics {
    box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.5);
    background: #FFFFFF;
    display: flex;
    height: 100%;

    .container-left {
      box-shadow: 2px 0px 4px 0px rgba(0, 0, 0, 0.17);
      border-radius: 2px 0px 0px 2px;
      padding-top: 15px;
      overflow: hidden;
      height: 100%;
      width: 160px;
      
      .tabs {
        padding: 0;
        margin: 0;
        
        .tabs-item {
          padding: 13px 24px;
          cursor: pointer;
          margin: 0;

          &.active {
            background: rgba(232, 150, 126, 0.19);
            color: #E8967E;
          }
        }
      }
    }

    .container-right {
      padding: 20px 24px;
      overflow: hidden;
      height: 100%;
      flex: 1;

      .head-container {
        justify-content: space-between;
        display: flex;
      }

      .table {
        height: calc(100% - 91px);
      }
    }
  }
}

</style>